using MongoDB.Driver;
using Sustainalytics.Entities;
using Sustainalytics.Synchronization.Validation.Internals;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Sustainalytics.Synchronization.Validation.Handlers.Common
{
    public abstract class HandlerWithGrouping<T> where T : IHasCompanyId
    {
        protected readonly IMongoCollection<T> ReferenceDataCollection;
        protected readonly IMongoCollection<T> ValidatedDataCollection;

        protected HandlerWithGrouping(ValidationMongoCollection<T> collections)
        {
            ValidatedDataCollection = collections.CurrentCollection;
            ReferenceDataCollection = collections.OldCollection;
        }

        public virtual Task<List<T>> GetReferenceElementsAsync(Guid companyId)
            => ReferenceDataCollection.Find(GetEntityFilter(companyId))
                    .Project<T>(GetProjectionDefinition())
                    .ToListAsync();

        public virtual Task<List<T>> GetValidatedElementAsync(Guid companyId)
            => ValidatedDataCollection.Find(GetEntityFilter(companyId))
                   .Project<T>(GetProjectionDefinition())
                   .ToListAsync();

        protected abstract ProjectionDefinition<T> GetProjectionDefinition();

        protected virtual FilterDefinition<T> GetEntityFilter(Guid companyId)
            => Builders<T>.Filter.Where(x => x.CompanyId == companyId);
    }
}
